<?php
/**
 * author: by wzb
 * time:2019/03-02
 */
class PostTracknumberToMangento extends Common
{
    public $storeinfo;
    public function PostData($shopid='',$trackingnumber='',$ShipperCode='',$orderid='',$shipmentid='',$storeinfo='',$magentoOrderid=''){
        $this->storeinfo = $storeinfo;
        //判断 是否发送过 声明
        if(empty($shipmentid) || $shipmentid == ''){
            if(!empty($trackingnumber) && !empty($ShipperCode) && !empty($orderid)){
                //创建 发送声明
                $this->GreatShipments($shopid,$orderid,$trackingnumber,$ShipperCode,$magentoOrderid);//创建运单
            }else{
                return false;
            }
        }else{
            //发送过则更新
            $usa_time = $this->PRCToPacific();//转换太平洋时间
            $this->Getinfo($orderid,$usa_time,$trackingnumber,$ShipperCode,$shipmentid);//查到信息 更新订单
        }
    }

 /**
    * 创建运单信息 
    * 
    * return ：entity id
**/
    public function GreatShipments($shopid,$orderid,$track_number,$carrier_code,$magentoOrderid){
        $buyerinfo = $this->byOiderIGetBuyerinfo($orderid);
        $msg = $this->byStoreIdgetStoreInfo($shopid);
        $storenamem = $buyerinfo['store_name'];
        $firstname = $buyerinfo['firstname'];
        $sendmsg = str_replace('$firstname',$firstname,$msg['msg']);
        $sendmsg = str_replace('$track_number',$track_number,$sendmsg);
        $sendmsg = str_replace('$carrier_code',strtoupper($carrier_code),$sendmsg);
        $title = $carrier_code;//快递标题
        $Data = array(
           /* 'items' => array(
                '0' => array(
                'extension_attributes' => array(),
                'order_item_id' => $order_item_id,
                'qty' => $qty,
                )
                ),*/
            'notify' => true,
            'appendComment' => true,
            'comment' => array(
                'extension_attributes' => array(),
                'comment' => $sendmsg,
                'is_visible_on_front' => 0
                ),
            'tracks' => array(
                '0' => array(
                    'extension_attributes' => array(),
                    'track_number' => $track_number,
                    'title' => $title,
                    'carrier_code' => $carrier_code
                    )
                ),
            'packages' => array(
                '0' => array(
                    'extension_attributes' => array()
                    )
                ),
            'arguments' => array(
                'extension_attributes' => array()
                )
        );
    $orderidinfo = $this->byOrderidGetOrderInfo($orderid);   
    $num = count($orderidinfo);
    $Data['items'] = array();
    for ($i=0;$i<$num;$i++) {
        $Data['items'][$i]['extension_attributes'] = array();
        $Data['items'][$i]['qty'] = $orderidinfo[$i]['pice_or_lotnums'];
        $Data['items'][$i]['order_item_id'] = $orderidinfo[$i]['item_id'];
    }
//$Data = '{"items":[{"extension_attributes": {},"order_item_id":'.$order_item_id.',"qty": 1}],"notify": true,"appendComment": true,"comment": {"extension_attributes": {},"comment": "string","is_visible_on_front": 0},"tracks": [{"extension_attributes": {},"track_number": '.$track_number.',"title": '.$title.',"carrier_code": '.$carrier_code.'}],"packages": [{"extension_attributes": {}}],"arguments": {"extension_attributes": {}}}';
       $Dlzorderapi = new \Dlzorderapi($this->storeinfo);
      // print_r($Dlzorderapi);
       $ship_entity_id = $Dlzorderapi->PostTracknumber($magentoOrderid,$Data);
      //  print_r($Data);
       /* $UpdateTime = date('YmdHis');
        $filename = $UpdateTime_cms.'log';
        $fp = fopen('/home/rylog/api/$filename', 'a+');
        fwrite($fp, print_r($Data, true));
        fclose($fp);*/
        print_r($ship_entity_id);
        if(is_array($ship_entity_id)){
            if(strpos($ship_entity_id['message'],'to be created') !== false || strpos($ship_entity_id['message'],'holded') !== false){
                $up_data = array('posttracknumber_status' => 3);
                $this->byOrderidUpdate($orderid,$up_data);
            }

            $ins_data = array('orderid' => $orderid,'msg' => $ship_entity_id['message']);
            $this->InsertINfo($ins_data);//记录错误信息
        }else{
            $up_data = array('shipmentid' => $ship_entity_id,'posttracknumber_status' => 1);
            $this->byOrderidUpdate($orderid,$up_data);//插入返回值
        }
        
        return $ship_entity_id;
    }
/**
    * 获取运单信息 
    * 
    * return ： data
**/
    public function Getinfo($orderid='',$usa_time='',$trackingnumber='',$ShipperCode='',$shipmentid=''){
        $Dlzorderapi = new \Dlzorderapi($this->storeinfo);
        $track_info = $Dlzorderapi->GetShippingInfo($ship_entity_id = $shipmentid);
        $tracks = array_key_exists('tracks',$track_info)?$track_info['tracks']:'';
        if(empty($tracks)){return false;}
        foreach($tracks as $val){
            $order_id = $val['order_id'];
            //$created_at = $val['created_at'];
            $entity_id = $val['entity_id'];
            $parent_id = $val['parent_id'];
           // $val['updated_at'];
            //$val['track_number'];
            //$val['title'];
            //$val['carrier_code'];
            $this->Updatetracknumberinfo($orderid,$usa_time,$trackingnumber,$ShipperCode,$order_id,$entity_id,$parent_id);//更新订单
        }
        return $track_info;
    }

/**
    * 获取运单信息 
    * 
    * return ： data
**/
    public function Updatetracknumberinfo($orderid='',$usa_time='',$trackingnumber='',$ShipperCode='',$order_id='',$entity_id='',$parent_id=''){
        $Data = array();
        $Data['entity']['order_id'] = $order_id;
        $Data['entity']['created_at'] = $usa_time;
        $Data['entity']['entity_id'] = $entity_id;
        $Data['entity']['parent_id'] = $parent_id;
        $Data['entity']['updated_at'] = '';
        $Data['entity']['weight'] = 0;
        $Data['entity']['qty'] = 0;
        $Data['entity']['description'] = '';
        $Data['entity']['extension_attributes'] = array();
        $Data['entity']['track_number'] = $trackingnumber;
        /***处理物流公司****/
        $carrier_code_str = strtolower($ShipperCode);
        if($carrier_code_str == 'dhl'){
            $expresscompany_des = 'DHL';
        }else if($carrier_code_str == 'fedex'){
            $expresscompany_des = 'Federal Express';
        }else if($carrier_code_str == 'ups'){
            $expresscompany_des = 'United Parcel Service';
        }else if($carrier_code_str == 'usps'){
            $expresscompany_des = 'United States Postal Service';
        }
        $Data['entity']['title'] = $expresscompany_des;
        $Data['entity']['carrier_code'] = $ShipperCode;
        $Dlzorderapi = new \Dlzorderapi($this->storeinfo);
        $track_info = $Dlzorderapi->EditPostTracknumberinfo($Data);
        //print_r($track_info);
        if(array_key_exists('message',$track_info)){
            $ins_data = array('orderid' => $orderid,'msg' => $track_info);
            $this->InsertINfo($ins_data);//记录错误信息
        }else{
            $up_data = array('posttracknumber_status' => 2);
            $rec_msg = json_encode($track_info);
            $ins_data = array('orderid' => $orderid,'msg' => $rec_msg.'--');
            $this->InsertINfo($ins_data);//记录错误信息
            $this->byOrderidUpdate($orderid,$up_data);//插入返回值
        }
        return $track_info;
    }








/**
 * 北京时间转太平洋时间
 * @param unknown_type $time
 */
    public function PRCToPacific($time=''){ 
         if(empty($time)){ 
             date_default_timezone_set('Asia/Shanghai');
             $date = date('Y-m-d H:i:s',strtotime("-8 hours"));
             //echo date('Y-m-d H:i:s',strtotime("-8 hours"))."<br/>";
         }
        /* date_default_timezone_set('Pacific/Apia');
         $date = date('Y-m-d H:i:s',$time);
         $time = strtotime($date."-8 hours");*/

         return $date; 
    }
}
	


